package com.sls.nzdapplication.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.core.TableConfig;
import com.esri.arcgisruntime.geometry.Point;
import com.hjq.shape.view.ShapeRadioButton;
import com.hjq.widget.view.ClearEditText;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.markfrain.formview.view.FormEditView;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.AppActivity;
import com.sls.nzdapplication.db.utils.DyEquipmentLineUtil;
import com.sls.nzdapplication.db.utils.DyEquipmentUtil;
import com.sls.nzdapplication.db.utils.SwitchEquipmentUtil;
import com.sls.nzdapplication.db.utils.SwitchUtil;
import com.sls.nzdapplication.model.DyEquipment;
import com.sls.nzdapplication.model.DyEquipmentLine;
import com.sls.nzdapplication.model.Switch;
import com.sls.nzdapplication.model.SwitchEquipment;
import com.sls.nzdapplication.model.TableViewData;
import com.sls.nzdapplication.ui.custom.CableWellPhotoView;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.util.UuidUtils;
import com.sls.nzdapplication.ui.custom.adapter.SearchAdapter;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import me.kareluo.ui.OptionMenu;
import me.kareluo.ui.OptionMenuView;
import me.kareluo.ui.PopupMenuView;

/**
 * 这是一个名为DyEquipmentActivity的Java类，它继承了AppCompatActivity类。
 * 这个类是一个活动，用于管理电压设备的信息。
 * 在这个类中，有很多控件，比如NiceSpinner、TextView、RadioGroup、ImageView、AutoCompleteTextView、ClearEditText等等。
 * 这些控件用于显示和输入电压设备的信息。在这个类中，还有很多方法，比如initView()、initData()、initListener()、onClick()等等。
 * 这些方法用于初始化控件、初始化数据、初始化监听器、处理点击事件等等。在这个类中，还有很多变量，比如clickEquipmentId、photoType、equipmentUtil、equipmentLineUtil、switchUtil、switchEquipmentUtil等等。
 * 这些变量用于存储电压设备的信息、存储照片类型、存储电压设备的工具类、存储电压设备线的工具类、存储开关的工具类、存储开关设备的工具类等等。
 * */
public class DyEquipmentActivity extends AppActivity implements View.OnClickListener,CableWellPhotoView.OnclickPhotoListener{

    NiceSpinner dxxhView,typeView,dxlxView,ljfsView,sbztView,gtxzView,gtczView,gtxhView,tgjsView,jcxsView,ssgtView;
    AutoCompleteTextView latView,lonView;
    RadioGroup sfnwView;
    ImageView qxxxRight,qdsbRight;
    TableRow qxxxInfoView,sbztInfoView,dxlxInfoView,xlxhInfoView,ljfsInfoView,sfnwInfoView,jsInfoView;
    LinearLayout dxgInfoView;
    TextView saveEquipmentView;
    private String clickEquipmentId = "";
    private String photoType;
    private DyEquipmentUtil equipmentUtil;
    private DyEquipmentLineUtil equipmentLineUtil;
    private CableWellPhotoView equipmentQmPhotoView;
    private CableWellPhotoView equipmentMpPhotoView;
    private CableWellPhotoView equipmentQxPhotoView;
    private CableWellPhotoView equipmentTtPhotoView;
    private CableWellPhotoView equipmentQzjPhotoView;
    private CableWellPhotoView equipmentJkPhotoView;
    private CableWellPhotoView equipmentJgPhotoView;
    private CableWellPhotoView equipmentBdPhotoView;
    private CableWellPhotoView equipmentBxPhotoView;
    private CableWellPhotoView equipmentBbPhotoView;
    private CableWellPhotoView equipmentBnPhotoView;

    private List<DyEquipment> dyEquipmentList;
    private SwitchEquipmentUtil switchEquipmentUtil;

    private String clickSwitchId = "";

    private String listclickSwitchId = "";

    private SwitchUtil switchUtil;

    private int code = 0;

    private AutoCompleteTextView autoCompleteTextViewNameView,qssbView;

    private int selectE = 0;

    private boolean isNew = true;

    private String lineId = "";

    private String equipmentId;

    private Double lat = 0.0;

    private Double lon = 0.0;

    private ClearEditText qxxxView;

    private String type;

    private EditText jsEditText;


    ShapeRadioButton sfnwOkView,sfnwNoView;

    PopWindow  popupWindow,popupWindow1;

    static final List<String> dxxhList = new ArrayList<>();
    static {
        dxxhList.add("JKLGYJ-10");
        dxxhList.add("JKLGYJ-16");
        dxxhList.add("JKLGYJ-120");
        dxxhList.add("JKLGYJ-185");
        dxxhList.add("JKLGYJ-2*6");
        dxxhList.add("JKLGYJ-4*35");
        dxxhList.add("JKLGYJ-4*50");
        dxxhList.add("JKLGYJ-70");
        dxxhList.add("JKLGYJ-95");
        dxxhList.add("JKLGYJS-2*16");
        dxxhList.add("JKLGYJS-2*35");
        dxxhList.add("JKLGYJS-4*35");
        dxxhList.add("JKLGYJS-4*50");
        dxxhList.add("JKLYJ-1×150");
        dxxhList.add("JKLYJ-1-50");
        dxxhList.add("JKLYJ-150/1");
        dxxhList.add("JKLYJ-1-70");
        dxxhList.add("JKLYJ-185");
        dxxhList.add("JKLYJ-1-95");
        dxxhList.add("JKLYJ-240/1");
        dxxhList.add("LGJ-16");
        dxxhList.add("LGJ-25");
        dxxhList.add("LGJ-35");
        dxxhList.add("LGJ-50");
        dxxhList.add("LGJ-50/8");
    }

    static final List<String> dydxxhList = new ArrayList<>();
    static {
        dydxxhList.add("YJV-4×35+1×16");
        dydxxhList.add("YJV22-4×50");
        dydxxhList.add("YJV22-4×35");
        dydxxhList.add("YJV22-4×240");
        dydxxhList.add("YJV22-4×120");
        dydxxhList.add("YJLV22-4x180+1x120");
        dydxxhList.add("YJLV22-4×50");
        dydxxhList.add("YJLV22-4*35");
        dydxxhList.add("YJLV22-4*185");
        dydxxhList.add("YJLV22-3*70+1*50");
        dydxxhList.add("YJLV22-3*70+1*35");
        dydxxhList.add("YJLV22-3*50+1*70");
        dydxxhList.add("YJLV22-3*120+1*95");
        dydxxhList.add("YJLV22-3*120+1*70");
        dydxxhList.add("YJLV22-1-4×95+1×50");
        dydxxhList.add("YJLV22-1-4×70+1×35");
        dydxxhList.add("YJLV22-1-4×50+1×25");
        dydxxhList.add("YJLV22-1-4×240+1×120");
        dydxxhList.add("YJLV22-1-3X120+1");
        dydxxhList.add("YJLKV22-3*95+1*120");
        dydxxhList.add("YJLKV22-3*25+1*16");
        dydxxhList.add("YJHLV22-0.6/1kV");
        dydxxhList.add("WDZ-YJV-4×240");
        dydxxhList.add("WDZB-YJY23-0.6/1kV-4×185");
        dydxxhList.add("WDZB-YJY23-0.6/1kV-4×150");
        dydxxhList.add("WDZB-YJY-0.6/1kV-1×150");
        dydxxhList.add("WDZB-YJY-0.6/1kV-1×120");
        dydxxhList.add("JKYJ-1*120");
        dydxxhList.add("BLV-0.6/1kV-4×95");
        dydxxhList.add("ZRYJV-4×95+1×50");
        dydxxhList.add("ZN-YJV-4×50+1×25");
        dydxxhList.add("ZCYJV-1-4*70+1*35");
        dydxxhList.add("ZCYJLV22-4×240");
    }

    static final List<String> tgjsList = new ArrayList<>();
    static {
        tgjsList.add("无同杆架设");
        tgjsList.add("1");
        tgjsList.add("2");
        tgjsList.add("3");
        }

    static final List<String> gtxzList = new ArrayList<>();
    static {

        gtxzList.add("直线");
        gtxzList.add("耐张");
    }

    static final List<String> gtczList = new ArrayList<>();
    static {
        gtczList.add("水泥杆");
        gtczList.add("角杆塔");
        gtczList.add("钢管塔");
        gtczList.add("钢管杆");
        gtczList.add("其他");
    }

    static final List<String> gtlxList = new ArrayList<>();
    static {
        gtlxList.add("水泥杆10米");
        gtlxList.add("水泥杆11米");
        gtlxList.add("水泥杆12米");
        gtlxList.add("水泥杆13米");
        gtlxList.add("水泥杆12.5米");
        gtlxList.add("水泥杆15米");
        gtlxList.add("水泥杆16米");
        gtlxList.add("水泥杆19米");
        gtlxList.add("水泥杆21米");
        gtlxList.add("钢杆10");
        gtlxList.add("钢杆12");
        gtlxList.add("钢杆12.5");
        gtlxList.add("钢杆13.5");
        gtlxList.add("钢杆15");
        gtlxList.add("钢杆16");
        gtlxList.add("钢杆18");
        gtlxList.add("钢杆19");
        gtlxList.add("钢杆21.5");
    }

    static final List<String> jcxsList = new ArrayList<>();
    static {
        jcxsList.add("水泥杆基础");
        jcxsList.add("钢筋混凝土");
        jcxsList.add("掏挖基础");
        jcxsList.add("灌注桩基础");
        jcxsList.add("嵌入式");
        jcxsList.add("素混");
        jcxsList.add("其他");
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_dy_equipment;
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void initView() {
        autoCompleteTextViewNameView = findViewById(R.id.equipment_name);
        dxxhView = (NiceSpinner) findViewById(R.id.dy_equipment_dxxh);
        dxxhView.attachDataSource(dxxhList);
        typeView = (NiceSpinner) findViewById(R.id.dy_equipment_type);
        dxlxView = (NiceSpinner) findViewById(R.id.dy_equipment_dxlx);
        List<String> projName3 = new ArrayList<>();
        projName3.add("绝缘");
        projName3.add("电缆");
        projName3.add("裸线");
        dxlxView.attachDataSource(projName3);

        dxlxView.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                    if(position == 1){
                        dxxhView.attachDataSource(dydxxhList);
                    }else{
                        dxxhView.attachDataSource(dxxhList);
                    }
            }
        });
        ljfsView = (NiceSpinner) findViewById(R.id.dy_equipment_ljfs);
        List<String> projName4 = new ArrayList<>();
        projName4.add("架空");
        projName4.add("入地");
        ljfsView.attachDataSource(projName4);
        sbztView = (NiceSpinner) findViewById(R.id.dy_equipment_sbzt);
        List<String> projName5 = new ArrayList<>();
        projName5.add("在运");
        projName5.add("停运");
        projName5.add("未投运");
        sbztView.attachDataSource(projName5);


        jsEditText = findViewById(R.id.dy_equipment_js_edit);
        jsInfoView = findViewById(R.id.jsInfoView);
        qssbView = findViewById(R.id.equipment_qdsb);
        qssbView.setFocusable(false);
        gtxzView = findViewById(R.id.dy_equipment_gtxz);
        gtxzView.attachDataSource(gtxzList);
        gtczView = findViewById(R.id.dy_equipment_gtcl);
        gtczView.attachDataSource(gtczList);
        gtxhView = findViewById(R.id.dy_equipment_gtxh);
        gtxhView.attachDataSource(gtlxList);
        tgjsView = findViewById(R.id.dy_equipment_tgjs);
        tgjsView.attachDataSource(tgjsList);
        jcxsView = findViewById(R.id.dy_equipment_jcxs);
        jcxsView.attachDataSource(jcxsList);
        ssgtView = findViewById(R.id.dy_equipment_ssgt);

        latView = findViewById(R.id.equipment_lat);
        lonView = findViewById(R.id.equipment_lon);
        sfnwView = findViewById(R.id.dy_equipment_sfnw);
        qxxxRight = findViewById(R.id.qxxx_right);
        qdsbRight = findViewById(R.id.qdsb_right);

        qxxxInfoView = findViewById(R.id.qxxx_info_view);
        sbztInfoView = findViewById(R.id.sbzt_info_view);
        dxlxInfoView = findViewById(R.id.dxlx_info_View);
        xlxhInfoView = findViewById(R.id.xlxh_info_View);
        ljfsInfoView = findViewById(R.id.ljfs_info_View);
        sfnwInfoView = findViewById(R.id.sfnw_info_View);
        qxxxView = findViewById(R.id.equipment_qxxx);
        dxgInfoView = findViewById(R.id.dxg_view);
        sfnwOkView = findViewById(R.id.snfw_ok);
        sfnwNoView = findViewById(R.id.snfw_no);

        equipmentQmPhotoView = findViewById(R.id.equipment_qm_photo);
        equipmentQmPhotoView.setOnclickPhotoListener(this);


        equipmentMpPhotoView = findViewById(R.id.equipment_mp_photo);
        equipmentMpPhotoView.setOnclickPhotoListener(this);

        equipmentQxPhotoView = findViewById(R.id.equipment_qx_photo);
        equipmentQxPhotoView.setOnclickPhotoListener(this);

        equipmentTtPhotoView = findViewById(R.id.equipment_tt_photo);
        equipmentTtPhotoView.setOnclickPhotoListener(this);

        equipmentQzjPhotoView = findViewById(R.id.equipment_qzj_photo);
        equipmentQzjPhotoView.setOnclickPhotoListener(this);



        equipmentJkPhotoView = findViewById(R.id.equipment_jk_photo);
        equipmentJkPhotoView.setOnclickPhotoListener(this);

        equipmentJgPhotoView = findViewById(R.id.equipment_jg_photo);
        equipmentJgPhotoView.setOnclickPhotoListener(this);

        equipmentBdPhotoView = findViewById(R.id.equipment_bd_photo);
        equipmentBdPhotoView.setOnclickPhotoListener(this);

        equipmentBxPhotoView = findViewById(R.id.equipment_bx_photo);
        equipmentBxPhotoView.setOnclickPhotoListener(this);

        equipmentBnPhotoView = findViewById(R.id.equipment_bn_photo);
        equipmentBnPhotoView.setOnclickPhotoListener(this);

        equipmentBbPhotoView = findViewById(R.id.equipment_bb_photo);
        equipmentBbPhotoView.setOnclickPhotoListener(this);

        saveEquipmentView = findViewById(R.id.save_equipment);

        initListener();

    }

    private void initListener(){
        qxxxRight.setOnClickListener(this);
        qdsbRight.setOnClickListener(this);
        saveEquipmentView.setOnClickListener(this);
        equipmentUtil = new DyEquipmentUtil(getApplicationContext());
        equipmentLineUtil = new DyEquipmentLineUtil(getApplicationContext());
        switchUtil = new SwitchUtil(getApplicationContext());
        switchEquipmentUtil = new SwitchEquipmentUtil(getApplicationContext());

    }

    @Override
    protected void initData() {
        List<String> types = new ArrayList<>();
        Intent intent = getIntent();
        if(null !=intent && intent.getStringExtra("equipmentId")!=null){
            isNew = false;
            // 从Intent中获取设备ID
            equipmentId = intent.getStringExtra("equipmentId");
            // 根据设备ID，查询并获取设备信息
            DyEquipment equipment = equipmentUtil.listOneDyEquipment(equipmentId);
            // 设置自动完成文本视图的设备名称
            autoCompleteTextViewNameView.setText(equipment.getName());

            jsEditText.setText(jsEditText.getText().toString());
            // 设置类型视图的设备类型
            typeView.setText(equipment.getType());
            // 将设备类型添加到类型列表
            types.add(equipment.getType());
            // 更新类型视图的数据源
            typeView.attachDataSource(types);
            // 设置纬度视图的设备纬度
            latView.setText(String.valueOf(equipment.getLat()));
            // 设置经度视图的设备经度
            lonView.setText(String.valueOf(equipment.getLon()));

            dxlxView.setText(equipment.getDxlx()==null?"":equipment.getDxlx());
            dxxhView.setText(equipment.getDlxh()==null?"":equipment.getDlxh());
            ljfsView.setText(equipment.getLxfs()==null?"":equipment.getLxfs());
            qxxxView.setText(equipment.getQxxx()==null?"":equipment.getQxxx());
            gtczView.setText(equipment.getGtcz()==null?"":equipment.getGtcz());
            gtxzView.setText(equipment.getGtxz()==null?"":equipment.getGtxz());
            gtxhView.setText(equipment.getGtxh()==null?"":equipment.getGtxh());
            jcxsView.setText(equipment.getJcxs()==null?"":equipment.getJcxs());
            sbztView.setText(equipment.getSbzt() ==null?"":equipment.getSbzt());
            tgjsView.setText(equipment.getTgjs()==null?"":equipment.getTgjs());
            if(dxlxView.getText().toString().equals("电缆")){
                dxxhView.attachDataSource(dydxxhList);
            }else{
                dxxhView.attachDataSource(dxxhList);
            }
            code = equipment.getCode();
            if(equipment.getSfnw()!=null && equipment.getSfnw().equals("是")){
                sfnwOkView.setChecked(true);
            }else{
                sfnwNoView.setChecked(true);
            }

            type = equipment.getType();
            lineId = equipment.getAreaId();
            if(!type.equals("配电箱")){
                DyEquipment ex = equipmentUtil.listOneDyEquipment(equipment.getPreviousEquipmentId());
                String sname = "";
                if(ex!=null){
                    if(ex.getType().equals("配电箱") || ex.getType().equals("变压器")){
                        if(switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId).size()>0){
                            clickSwitchId = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId).get(0).getSid();
                            sname = switchUtil.listOneSwitch(clickSwitchId).getName();
                        }
                    }
                    qssbView.setText(ex.getName()+sname);
                    clickEquipmentId = equipment.getPreviousEquipmentId();
                }
            }
            if(type.equals("低压")){
                dxgInfoView.setVisibility(View.VISIBLE);
                equipmentTtPhotoView.setVisibility(View.VISIBLE);
            }
            if(type.equals("墙支架")){
                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentTtPhotoView.setVisibility(View.GONE);
            }
            if(type.equals("拐点")){
                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentTtPhotoView.setVisibility(View.GONE);
                sbztInfoView.setVisibility(View.GONE);
                qxxxInfoView.setVisibility(View.GONE);
            }
            if(type.equals("电缆井")){
                sbztInfoView.setVisibility(View.GONE);
                qxxxInfoView.setVisibility(View.GONE);
                dxlxInfoView.setVisibility(View.GONE);
                sbztInfoView.setVisibility(View.GONE);
                ljfsInfoView.setVisibility(View.GONE);
                xlxhInfoView.setVisibility(View.GONE);
                sfnwInfoView.setVisibility(View.GONE);

                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentQzjPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);

                equipmentJkPhotoView.setVisibility(View.VISIBLE);
                equipmentJgPhotoView.setVisibility(View.VISIBLE);
                equipmentBdPhotoView.setVisibility(View.VISIBLE);
                equipmentBxPhotoView.setVisibility(View.VISIBLE);
                equipmentBnPhotoView.setVisibility(View.VISIBLE);
                equipmentBbPhotoView.setVisibility(View.VISIBLE);
                jsInfoView.setVisibility(View.VISIBLE);
                jsEditText.setText(equipment.getJscm());
//                upLatAndLon.setVisibility(View.VISIBLE);
            }
        }
        else if(null !=intent && intent.getBundleExtra("params") != null){
            // 从Intent中获取名为"params"的Bundle
            Bundle bundle = intent.getBundleExtra("params");
            // 从Bundle中分别获取经纬度和类型，并将类型添加到types集合中
            lat = bundle.getDouble("lat");
            lon = bundle.getDouble("lon");
            type = bundle.getString("type");
            types.add(type);
            // 绑定数据源到typeView
            typeView.attachDataSource(types);
            // 从Bundle中获取线路ID、点击设备ID和点击开关ID
            lineId = bundle.getString("lineId");
            clickEquipmentId = bundle.getString("clickE");
            clickSwitchId = bundle.getString("clickS");
            // 将点击开关ID赋值给listclickSwitchId
            listclickSwitchId = clickSwitchId;
            // 生成一个新的设备ID
            equipmentId = UuidUtils.getStringID();
            // 设置经纬度和类型到对应的视图中
            latView.setText(String.valueOf(lat));
            lonView.setText(String.valueOf(lon));
            typeView.setText(type);
            // 初始化动态设备对象和相关名称变量
            DyEquipment ex=null;
            String sname = "";
            String exname = "";

            if(!type.equals("配电箱")){
                ex = equipmentUtil.listOneDyEquipment(clickEquipmentId);
                Switch sw = switchUtil.listOneSwitch(clickSwitchId);
                if(sw!=null){
                    sname = ex.getName()+sw.getName();
                    exname = sw.getName();

                }else{
                    sname = ex.getName();
                    exname = sname;
                }
                qssbView.setText(sname);
            }
            if(equipmentUtil.queryDyEquipmentByAreaIdAndType(lineId,type).size()==0){
                if(type.equals("墙支架")){
                    code = 1;
                }else{
                    code = 0;
                }

            }else{
                DyEquipment dye = equipmentUtil.queryDyEquipmentByAreaIdAndType(lineId,type).get(0);
                if(type.equals("低压")){
                    code = dye.getCode()+1;
                }else{
                    code = dye.getCode();
                }
            }
            if(type.equals("低压")){
                dxgInfoView.setVisibility(View.VISIBLE);
                equipmentTtPhotoView.setVisibility(View.VISIBLE);
                List<DyEquipment> gtlists = equipmentUtil.queryDyEquipmentByAreaIdAndType(lineId,type);

                if(gtlists.size()>0){
                    String gtname = gtlists.get(0).getName();
                    int l = 0;
                    char[] gtnames = gtname.toCharArray();
                    for(int i = gtnames.length;i>0;i--){
                        if(!isNumber(String.valueOf(gtnames[i-1]))){
                            l=i;
                            break;
                        }
                    }
                    if(l==gtname.length()){
                        autoCompleteTextViewNameView.setText(gtname + Utils.getName(code));
                    }
                    else if(l!=gtname.length()-3 && l<gtname.length()){
                        autoCompleteTextViewNameView.setText(gtname.substring(0,l)+ + (code));
                    }else{
                        autoCompleteTextViewNameView.setText(gtname.substring(0,gtname.length()-3)+ Utils.getName(code));
                    }
                }else{
                    autoCompleteTextViewNameView.setText("低压杆塔"+ Utils.getName(code));
                }

                ljfsView.setText("架空");
                gtxzView.setText("直线");
                gtczView.setText("水泥杆");
                gtxhView.setText("水泥杆10米");
                tgjsView.setText("无同杆架设");
                jcxsView.setText("水泥杆基础");

            }else if(type.equals("墙支架")){
                String myname = customName(ex.getType(),type,exname,ex.getId());
                autoCompleteTextViewNameView.setText(myname);
                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentTtPhotoView.setVisibility(View.GONE);

            }else if(type.equals("拐点")){
                sbztInfoView.setVisibility(View.GONE);
                qxxxInfoView.setVisibility(View.GONE);
                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentTtPhotoView.setVisibility(View.GONE);
                equipmentQzjPhotoView.setVisibility(View.GONE);
                String myname = customName(ex.getType(),type,exname,ex.getId());
                autoCompleteTextViewNameView.setText(myname);
            }else if (type.equals("电缆井")){
                sbztInfoView.setVisibility(View.GONE);
                qxxxInfoView.setVisibility(View.GONE);
                dxlxInfoView.setVisibility(View.GONE);
                sbztInfoView.setVisibility(View.GONE);
                ljfsInfoView.setVisibility(View.GONE);
                xlxhInfoView.setVisibility(View.GONE);
                sfnwInfoView.setVisibility(View.GONE);

                equipmentQmPhotoView.setVisibility(View.GONE);
                equipmentQxPhotoView.setVisibility(View.GONE);
                equipmentQzjPhotoView.setVisibility(View.GONE);
                equipmentMpPhotoView.setVisibility(View.GONE);

                equipmentJkPhotoView.setVisibility(View.VISIBLE);
                equipmentJgPhotoView.setVisibility(View.VISIBLE);
                equipmentBdPhotoView.setVisibility(View.VISIBLE);
                equipmentBxPhotoView.setVisibility(View.VISIBLE);
                equipmentBnPhotoView.setVisibility(View.VISIBLE);
                equipmentBbPhotoView.setVisibility(View.VISIBLE);
                jsInfoView.setVisibility(View.VISIBLE);
                String myname = customName(ex.getType(),type,exname,ex.getId());
                autoCompleteTextViewNameView.setText(myname);

            }else{
                String myname = customName(ex.getType(),type,exname,ex.getId());
                autoCompleteTextViewNameView.setText(myname);
                equipmentQzjPhotoView.setVisibility(View.GONE);
            }
        }
        equipmentQmPhotoView.initData("dyEquipment",equipmentId,"qm");
        equipmentMpPhotoView.initData("dyEquipment",equipmentId,"mp");
        equipmentQxPhotoView.initData("dyEquipment",equipmentId,"qx");
        equipmentTtPhotoView.initData("dyEquipment",equipmentId,"tt");
        equipmentQzjPhotoView.initData("dyEquipment",equipmentId,"qzj");

        equipmentJkPhotoView.initData("dyEquipment",equipmentId,"jk");
        equipmentJgPhotoView.initData("dyEquipment",equipmentId,"jg");
        equipmentBdPhotoView.initData("dyEquipment",equipmentId,"bd");
        equipmentBxPhotoView.initData("dyEquipment",equipmentId,"bx");
        equipmentBnPhotoView.initData("dyEquipment",equipmentId,"bn");
        equipmentBbPhotoView.initData("dyEquipment",equipmentId,"bb");



        List<DyEquipment> dyEquipmentList = equipmentUtil.queryDyEquipmentByAreaIdAndType(lineId,type);
        List<String> names = new ArrayList<>();
        for(DyEquipment dyEquipment:dyEquipmentList){
            names.add(dyEquipment.getName());
        }


    }


    private void saveData(){
        DyEquipment equipment;
        String name = autoCompleteTextViewNameView.getText().toString();
        if(name.equals("")){
            Toasty.error(getApplicationContext(), "设备名称不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        if((equipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).size()>0 && isNew) || (!isNew && equipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).size()>0 && !equipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,name).get(0).getId().equals(equipmentId))){
            Toasty.error(getApplicationContext(), "设备已存在", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(typeView.getText().toString().equals("")){
            Toasty.error(getApplicationContext(), "设备类型不能为空", Toast.LENGTH_LONG, true).show();
            return;
        }
        if(isNew){
            equipment = new DyEquipment();
        }else{
            equipment = equipmentUtil.listOneDyEquipment(equipmentId);
        }
        equipment.setId(equipmentId);
        equipment.setName(name);
        equipment.setLon(Double.valueOf(lonView.getText().toString()));
        equipment.setLat(Double.valueOf(latView.getText().toString()));
        equipment.setType(typeView.getText().toString());
        String jsText = jsEditText.getText().toString();
        equipment.setJscm(jsText);
        // 判断是否为新设备
        if(!isNew){
            // 如果当前设备的ID与之前的设备ID不相同
            if(!clickEquipmentId.equals(equipment.getPreviousEquipmentId())){
                // 查询当前设备与之前设备之间的所有设备线
                List<DyEquipmentLine> equipmentLines = equipmentLineUtil.queryEquipmentLineByStartAndEnd(equipment.getPreviousEquipmentId(),equipmentId);
                // 删除这些设备线
                for(DyEquipmentLine dyEquipmentLine:equipmentLines){
                    equipmentLineUtil.deleteDyEquipmentLine(dyEquipmentLine);
                }

                // 创建新的设备线
                DyEquipmentLine equipmentLine = new DyEquipmentLine();
                equipmentLine.setId(UuidUtils.getStringID());
                equipmentLine.setStartEquipmentId(clickEquipmentId);
                equipmentLine.setEndEquipmentId(equipmentId);
                // 根据设备类型设置设备线的类型
                if(type.equals("墙支架")){
                    equipmentLine.setType("2");
                }
                else if(type.equals("低压")){
                    equipmentLine.setType("3");
                }else {
                    equipmentLine.setType("1");
                }
                equipmentLine.setLineId(lineId);
                // 插入新的设备线
                equipmentLineUtil.insertDyEquipmentLine(equipmentLine);
            }
        }

        equipment.setPreviousEquipmentId(clickEquipmentId);
        equipment.setDxlx(dxlxView.getText().toString());
        equipment.setDlxh(dxxhView.getText().toString());
        equipment.setLxfs(ljfsView.getText().toString());
        equipment.setQxxx(qxxxView.getText()==null?"":qxxxView.getText().toString());
        if(type.equals("低压")){
            equipment.setGtxh(gtxhView.getText().toString());
            equipment.setGtcz(gtczView.getText().toString());
            equipment.setTgjs(tgjsView.getText().toString());
            equipment.setGtxz(gtxzView.getText().toString());
            equipment.setJcxs(jcxsView.getText().toString());
        }

        equipment.setSbzt(sbztView.getText().toString());

        equipment.setCode(code);
            if(((ShapeRadioButton) findViewById(sfnwView.getCheckedRadioButtonId())).getText().toString().equals("是")){
                equipment.setSfnw("是");
            }else{
                equipment.setSfnw("否");
            }

        equipment.setCreateTime(new Date());
        equipment.setAreaId(lineId);
        if(isNew){
            equipmentUtil.insertDyEquipment(equipment);
            if(!type.equals("配电箱")){
                DyEquipmentLine equipmentLine = new DyEquipmentLine();
                equipmentLine.setId(UuidUtils.getStringID());
                equipmentLine.setStartEquipmentId(clickEquipmentId);
                equipmentLine.setEndEquipmentId(equipmentId);
                equipmentLine.setJscm(jsEditText.getText().toString());
                if(type.equals("墙支架")){
                    equipmentLine.setType("2");
                }
                else if(type.equals("低压")){
                    equipmentLine.setType("3");
                }
                else if (type.equals("电缆井")){
                    equipmentLine.setType("4");
                }
                else{
                    equipmentLine.setType("1");
                }

                equipmentLine.setLineId(lineId);
                equipmentLineUtil.insertDyEquipmentLine(equipmentLine);
            }
        }else{
            equipmentUtil.updateDyEquipment(equipment);
        }

        if(!clickSwitchId.equals("")){
            List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
            for(SwitchEquipment switchEquipment :switchEquipments){
                switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
            }
            SwitchEquipment switchEquipment = new SwitchEquipment();
            switchEquipment.setId(UuidUtils.getStringID());
            switchEquipment.setSid(clickSwitchId);
            switchEquipment.setEid(equipmentId);
            switchEquipmentUtil.insertSwitchEquipment(switchEquipment);
        }
        DyEquipment dyEquipment = equipmentUtil.listOneDyEquipment(clickEquipmentId);
        if(!dyEquipment.getType().equals("配电箱")){
            List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
            for(SwitchEquipment switchEquipment :switchEquipments){
                switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
            }
        }
        Toasty.success(getApplicationContext(), "保存成功", Toast.LENGTH_LONG, true).show();
        isNew = false;
    }

    private void initProject(){
        dyEquipmentList = equipmentUtil.queryDyEquipmentByAreaIdNoself(lineId,equipmentId);
        List<String> projName = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,500);
        List<DyEquipment> list = dyEquipmentList;
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        for(DyEquipment dyEquipment:list){
            projName.add(dyEquipment.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(dyEquipmentList.get(i).getId().equals(equipmentId)){
                    Toasty.error(getApplicationContext(), "不能选择当前设备", Toast.LENGTH_LONG, true).show();
                }else{
                    selectE = i;
                    clickEquipmentId = dyEquipmentList.get(i).getId();
                    if(dyEquipmentList.get(i).getType().equals("配电箱")){
                        initSwitch();
                    }else{
                        qssbView.setText(dyEquipmentList.get(i).getName());
                    }
                    popupWindow.dismiss();
                }

            }
        });
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, projName);
        listView.setAdapter(adapter);
        popupWindow= new PopWindow.Builder(DyEquipmentActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择前端设备")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();

    }

    private void initSwitch(){
        List<Switch> switchList = switchUtil.querySwitchByeId(clickEquipmentId);
        List<String> sName = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,500);
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        for(Switch sw:switchList){
            sName.add(sw.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                clickSwitchId = switchList.get(i).getId();
                qssbView.setText(dyEquipmentList.get(selectE).getName()+switchList.get(i).getName());
                popupWindow1.dismiss();


            }
        });
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, sName);
        listView.setAdapter(adapter);
        popupWindow1 = new PopWindow.Builder(DyEquipmentActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择开关")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();

    }

    private void clearEquipment(){
        List<DyEquipmentLine> equipmentLineList = equipmentLineUtil.queryEquipmentLineByEid(equipmentId);
        for(DyEquipmentLine equipmentLine:equipmentLineList){
            equipmentLineUtil.deleteDyEquipmentLine(equipmentLine);
        }
        List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentByEid(equipmentId);
        for(SwitchEquipment switchEquipment:switchEquipments){
            switchEquipmentUtil.deleteSwitchEquipment(switchEquipment);
        }
        equipmentUtil.deleteDyEquipment(equipmentUtil.listOneDyEquipment(equipmentId));
        this.finish();
    }

    private void openMenu(View view, List<OptionMenu> optionMenus, ClearEditText contentView){
        PopupMenuView menuView = new PopupMenuView(getApplicationContext());
        menuView.setMenuItems(optionMenus);
        menuView.setOrientation(LinearLayout.VERTICAL);
        menuView.setOnMenuClickListener(new OptionMenuView.OnOptionMenuClickListener() {
            @Override
            public boolean onOptionMenuClick(int position, OptionMenu menu) {
                contentView.setText(menu.getTitleRes());
                return true;
            }
        });

        menuView.show(view);
    }

    @Override
    public void onClick(View view) {
        if(view==qdsbRight){
            initProject();
        }
        if(view == qxxxRight){
            openMenu(qxxxRight, Arrays.asList(new OptionMenu(R.string.qxxx_1),new OptionMenu(R.string.qxxx_2),new OptionMenu(R.string.qxxx_3),
                    new OptionMenu(R.string.qxxx_5),new OptionMenu(R.string.qxxx_6),new OptionMenu(R.string.qxxx_7),
                    new OptionMenu(R.string.qxxx_8),new OptionMenu(R.string.qxxx_9),new OptionMenu(R.string.qxxx_10),
                    new OptionMenu(R.string.qxxx_11),new OptionMenu(R.string.qxxx_12),new OptionMenu(R.string.qxxx_13),
                    new OptionMenu(R.string.qxxx_14),new OptionMenu(R.string.qxxx_15),new OptionMenu(R.string.qxxx_16),new OptionMenu(R.string.qxxx_17)),qxxxView);
        }
        if(view == saveEquipmentView){
            saveData();
        }
//        if (view == upLatAndLon){
//            startActivity(new Intent(DyEquipmentActivity.this,DyMapActivity.class));
//        }
    }

    @Override
    public void onRightClick(View view) {
        new PopWindow.Builder(this)
                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .setTitle("你确定要删除当前数据！！")
                .addItemAction(new PopItemAction("确定", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
                        clearEquipment();
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .show();
    }

    @Override
    public void onClickPhotoListener(String type) {
        photoType = type;
    }

    @Override
    public void openPhotoView(String path) {
        Intent intent = new Intent(DyEquipmentActivity.this,PhotoDetailActivity.class);
        intent.putExtra("filePath",path);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(photoType.equals("qm")) {
            equipmentQmPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("mp")) {
            equipmentMpPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("qx")) {
            equipmentQxPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("tt")) {
            equipmentTtPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("qzj")) {
            equipmentQzjPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }


        if(photoType.equals("jk")) {
            equipmentJkPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("jg")) {
            equipmentJgPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("bd")) {
            equipmentBdPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("bx")) {
            equipmentBxPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("bn")) {
            equipmentBnPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
        if(photoType.equals("bb")) {
            equipmentBbPhotoView.onActivityResultListener(requestCode, resultCode, data);
        }
    }

    private boolean isNumber(String str){
        try {
            Integer.parseInt(str);
            return true;
        } catch(Exception e){
            return false;
        }
    }

    private int getcode(String name){
        String code = name.substring(name.length()-3,name.length());
        if(isNumber(code)){
            return Integer.parseInt(code)+1;
        }
        return 0;
    }

    private String typeName(String type){
        switch (type){
            case "墙支架":
                return "墙";
            case "拐点":
                return "GD";
            case "低压":
                return "低压杆塔";
        }
        return type;
    }

    /**
     * 获取前一个设备
     * */
    private DyEquipment getexEq(String type ,String exid){
        DyEquipment dyEquipment = equipmentUtil.listOneDyEquipment(exid);
        if(!dyEquipment.getType().equals(type)){
            if(switchEquipmentUtil.querySwitchEquipmentByEid(dyEquipment.getId()).size()>0){
                listclickSwitchId = switchEquipmentUtil.querySwitchEquipmentByEid(dyEquipment.getId()).get(0).getSid();
            }
            return dyEquipment;
        }else{
            if(switchEquipmentUtil.querySwitchEquipmentByEid(dyEquipment.getId()).size()>0){
                listclickSwitchId = switchEquipmentUtil.querySwitchEquipmentByEid(dyEquipment.getId()).get(0).getSid();
            }
            return getexEq(dyEquipment.getType(),dyEquipment.getPreviousEquipmentId());
        }
    }

    /**
     * 获取最大的编号
     * */
    private int bigCode(String type ,String exid){
        DyEquipment dyEquipment = getexEq(type ,exid);
        return getbigcode(dyEquipment.getId(),type);
    }

    /**
     * 获取大编码
     * @param exid 设备id
     * @param type 设备类型
     * @return 大编码
     */
    private  int getbigcode(String exid,String type){
        DyEquipment dyEquipment = equipmentUtil.listOneDyEquipment(exid);
        List<DyEquipment> dyEquipmentList = new ArrayList<>() ;
        if(dyEquipment.getType().equals("配电箱") && !listclickSwitchId.equals("")){
            List<SwitchEquipment> switchEquipments = switchEquipmentUtil.querySwitchEquipmentBySid(listclickSwitchId);
            for(SwitchEquipment switchEquipment:switchEquipments){
                DyEquipment dyEquipment1 = equipmentUtil.listOneDyEquipment(switchEquipment.getEid());
                if(dyEquipment1.getType().equals(type)){
                    dyEquipmentList.add(dyEquipment1);
                }
            }
        }else{
            dyEquipmentList = equipmentUtil.queryDyEquipmentByAreaIdAndexqIdAndType(lineId,exid,type);
        }

        List<String> stringList = new ArrayList<>();
        for(DyEquipment dyEquipment1:dyEquipmentList){
            stringList.addAll(getallName(new ArrayList<>(),dyEquipment1));
        }
        int i = -1;
        for(String s:stringList){
            char[] namelist = s.toCharArray();
            int l = 0;
            for(int j = namelist.length;j>0;j--){
                if(!isNumber(String.valueOf(namelist[j-1]))){
                    l=j;
                    break;
                }
            }
            if(isNumber(s.substring(l,s.length()))){
                int n = Integer.parseInt(s.substring(l,s.length()));
                if(n>i){
                    i = n;
                }
            }
        }
        return i;
    }

    /**
     * 获取所有名称
     * */
    private List<String> getallName(List<String> list,DyEquipment dyEquipment){
        List<String>  list1 = list;
        list1.add(dyEquipment.getName());
        List<DyEquipment> dyEquipmentList = equipmentUtil.queryDyEquipmentByAreaIdAndexqIdAndType(lineId,dyEquipment.getId(),dyEquipment.getType());
        for(DyEquipment dyEquipment1:dyEquipmentList){
            if(dyEquipment1.getType().equals(dyEquipment.getType())){
                list1.addAll(getallName(list1,dyEquipment1));
            }
        }
        return list1;
    }

    /**
     * 自定取名
     * */
    private String customName(String exType,String type ,String exname,String exid){
        String myName = "";
        if(exType.equals(type)){
            char[] namelist = exname.toCharArray();
            int l = 0;
            for(int i = namelist.length;i>0;i--){
                if(!isNumber(String.valueOf(namelist[i-1]))){
                    l=i;
                    break;
                }
            }
            if(l == exname.length()){
                myName = exname+Utils.getName(0);
            }
            else if(l!=exname.length()-3 && l<exname.length()){
                myName = exname.substring(0,l)+((Integer.parseInt(exname.substring(l,exname.length())))+1);
            }else{
                myName = exname.substring(0,exname.length()-3)+Utils.getName(getcode(exname));
            }
            if(equipmentUtil.queryDyEquipmentByAreaIdAndName(lineId,myName).size()>0 && (type.equals("墙支架") || type.equals("拐点"))){
                myName = "未命名"+code+myName;
                code = code+1;
            }else{
                if((type.equals("墙支架") || type.equals("拐点"))){
                    myName = myName;
                }else{
                    if(l == exname.length()){
                        myName = exname+ Utils.getName(bigCode(type,exid)+1);
                    }
                    else if(l!=exname.length()-3 && l<exname.length()){
                        myName = exname.substring(0,l)+(bigCode(type,exid)+1);
                    }else{
                        myName = exname.substring(0,exname.length()-3)+Utils.getName(bigCode(type,exid)+1);
                    }
                }
            }
        }else{
            int i = getbigcode(exid,type);
            if(type.equals("墙支架") && i == -1){
                myName = exname+typeName(type)+Utils.getName(i+2);
            }else{
                myName = exname+typeName(type)+Utils.getName(i+1);
            }

        }
        return myName;
    }
}